import { ref } from "vue";
import { getEffectiveCountry } from "@/apis/country";
import type { CountryCodeListType } from "@/type/countryType";

//获取有效国家列表的数据

//国家列表code码列表数据
const countryCodeList = ref<CountryCodeListType[]>([]);

// 初始化时从sessionStorage获取数据
const initCountryCodeList = () => {
  const storedData = sessionStorage.getItem("countryCodeList");
  if (storedData) {
    try {
      countryCodeList.value = JSON.parse(storedData);
    } catch (error) {
      console.error("解析国家列表数据失败:", error);
      countryCodeList.value = [];
    }
  }
};

// 初始化数据
initCountryCodeList();

export default () => {
  //发送请求拿取有效国家列表数据
  const getCountryCodeListFetch = () => {
    getEffectiveCountry().then((res) => {
      if (res.data) {
        countryCodeList.value = res.data;
        sessionStorage.setItem(
          "countryCodeList",
          JSON.stringify(countryCodeList.value)
        );
      }
    });
  };

  //获取本地的国家code码列表数据
  const getCountryCodeList = () => {
    if (countryCodeList.value.length > 0) {
      return countryCodeList.value;
    }
    const storedData = sessionStorage.getItem("countryCodeList");
    if (storedData) {
      try {
        countryCodeList.value = JSON.parse(storedData);
      } catch (error) {
        console.error("解析国家列表数据失败:", error);
        countryCodeList.value = [];
      }
    }
    return countryCodeList.value;
  };

  return {
    countryCodeList,
    getCountryCodeListFetch,
    getCountryCodeList,
  };
};
